﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Collections;

using umbraco.BasePages;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.propertytype;
using umbraco.interfaces;
#if UMB45
using umbraco.presentation.nodeFactory;
#else
using umbraco.NodeFactory;
#endif

namespace umbraco.blog4.usercontrols.dashboard {
	public partial class CreatePost : UserControl {
		private ArrayList _dataFields = new ArrayList();
		private int _parentId = -1;
		private umbraco.editorControls.tinyMCE3.TinyMCE _tinymce = null;

		protected void Page_Load(object sender, EventArgs e) {
			if (!IsPostBack) {
				// Load blog type options
				List<DocumentType> dts = BlogLibrary.TypeList("BlogPost");
				lstBlogTypes.DataSource = dts;
				lstBlogTypes.DataValueField = "ID";
				lstBlogTypes.DataTextField = "Text";
				lstBlogTypes.DataBind();
			}

			if (_tinymce != null) {
				umbraco.uicontrols.TabView tabview = GetDashboardPanel();
				if (_tinymce.config["umbraco_toolbar_id"] != null)
					_tinymce.config.Remove("umbraco_toolbar_id");
				_tinymce.config.Add("umbraco_toolbar_id", tabview.ClientID + "_tab01layer_menu_sl");
			}
		}

		protected void lstBlogs_SelectedIndexChanged(object sender, EventArgs e) {
			SetBlogRoot();
		}

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            // get the blog doctype
            List<DocumentType> blogType = BlogLibrary.TypeList("BlogPost");

            // find any blogs within range of the current user
            SetBlogRoot();

            if (_parentId <= 0) {
                blogpostCreatorNoBlog.Visible = true;
                blogpostCreator.Visible = false;
            } else {
                // load all properties from the first tab
                umbraco.cms.businesslogic.ContentType.TabI contentTab = blogType.First().getVirtualTabs[0];
                #if UMB45
				foreach (PropertyType pt in contentTab.PropertyTypes) {
                #else
                foreach (PropertyType pt in contentTab.GetPropertyTypes(blogType.First().Id)) {
                #endif
                    IDataType dt = pt.DataTypeDefinition.DataType;

                    // test for tinymce - we need to tell it to add icons to the dashboard menu
                    if (dt.Id == new Guid("{5E9B75AE-FACE-41c8-B47E-5F4B0FD82F83}")) {
                        _tinymce = (umbraco.editorControls.tinyMCE3.TinyMCE)dt.DataEditor;
                    }

                    dt.DataEditor.Editor.ID = pt.Alias;
                    _dataFields.Add(dt);

                    IData df = pt.DataTypeDefinition.DataType.Data;

                    blogpostControls.Controls.Add(new LiteralControl("<p><label for=\"" + dt.DataEditor.Editor.ClientID
                        + "\"><strong>" + pt.Name + "</strong>" + "</label>"));
                    blogpostControls.Controls.Add(dt.DataEditor.Editor);
                    blogpostControls.Controls.Add(new LiteralControl("</p>"));
                }
            }
        }

		private umbraco.uicontrols.TabView GetDashboardPanel() {
			umbraco.uicontrols.TabView tabview =
				(umbraco.uicontrols.TabView)FindControlRecursive(this.Page.Master, "dashboardTabs");
			return tabview;
		}

		public static Control FindControlRecursive(Control Root, string Id) {
			if (Root.ID == Id) return Root;

			foreach (Control Ctl in Root.Controls) {
				Control FoundCtl = FindControlRecursive(Ctl, Id);
				if (FoundCtl != null) return FoundCtl;
			}
			return null;
		}

        private void SetBlogRoot() {
            if (_parentId == -1) {
                string sql = "select id, path from umbracoNode " +
                             "inner join cmsContent on cmsContent.nodeId = umbracoNode.id " +
                             "inner join cmsContentType on cmsContentType.nodeId = cmsContent.contentType " +
                             "where cmsContentType.Alias IN ({0}) and path not like '%-20%' and path like '%{1}%' " +
                             "order by path";

                string userStartNode = (UmbracoEnsuredPage.CurrentUser.StartNodeId != -1)
                                           ? String.Format(",{0},", UmbracoEnsuredPage.CurrentUser.StartNodeId)
                                           : String.Format("{0},", UmbracoEnsuredPage.CurrentUser.StartNodeId);
                sql = String.Format(sql, BlogLibrary.DocumentTypesAsString("Blog"), userStartNode);

                _parentId = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>(sql);
            }
        }

		protected void lstBlogTypes_SelectedIndexChanged(object sender, EventArgs e) {
			//List<Document> blogs = new List<Document>();
			//Find BLOG or BLOG-derived document WHERE getProperty("BlogAliasType") == selectedValue
			List<DocumentType> blogs = BlogLibrary.TypeList("Blog");

			umbraco.cms.businesslogic.Content[] ct = new umbraco.cms.businesslogic.Content[0];
			foreach (DocumentType dt in blogs) {
				umbraco.cms.businesslogic.Content[] blogNodes = Document.getContentOfContentType(new ContentType(dt.Id));
				if ((blogNodes.Length > 0) &&
					(blogNodes[0].getProperty("blogPostDocumentType") != null) &&
					(!string.IsNullOrEmpty(blogNodes[0].getProperty("blogPostDocumentType").Value.ToString())) &&
					(blogNodes[0].getProperty("blogPostDocumentType").Value.ToString() == lstBlogTypes.SelectedValue.ToString())) {
					ct = blogNodes;
					break;
				}
			}
			lstBlogsOfType.DataSource = ct;
			lstBlogsOfType.DataTextField = "Text";
			lstBlogsOfType.DataValueField = "Id";
			lstBlogsOfType.DataBind();
		}

        protected void createPost_Click(object sender, EventArgs e) {

            // Save properties
            char[] sp = new char[] { char.Parse(",") };
            Document blogpost = Document.MakeNew(title.Text,
                new DocumentType(int.Parse(lstBlogTypes.SelectedValue)),
                UmbracoEnsuredPage.CurrentUser,
                int.Parse(lstBlogsOfType.SelectedValue));

            // hack to make the tagger datatype work as it relys either on id in request collection
            // or current page in nodefactory
            // SetRequestId(blogpost.Id.ToString());

            foreach (IDataType df in _dataFields) {
                // if (df.DataTypeName.ToLower() != "tags") {
                DefaultData ddf = (DefaultData)df.Data;
                df.Data.PropertyId = ddf.NodeId;
                df.DataEditor.Save();
            } /* else {
					DataEditor dxf = (DataEditor)df.DataEditor;
					DefaultData ddf = (DefaultData)df.Data;
					df.Data.PropertyId = ddf.NodeId;
					dxf.Save();
				} */
            // }

            if (publish.Checked) {
                blogpost.Publish(UmbracoEnsuredPage.CurrentUser);
                umbraco.library.UpdateDocumentCache(blogpost.Id);
            }

            Response.Redirect("editContent.aspx?id=" + blogpost.Id, true);
        }

		// Version control can tell you what was here previously ;-) (CodeGecko)
	}
}
